package com.cheer.util;

import cn.hutool.core.util.URLUtil;
import cn.hutool.poi.excel.ExcelWriter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.Map;

@Slf4j
public class ExcelUtil {

    /**
     * 导出
     *
     * @param list        导出数据
     * @param headerAlias 表头字段
     * @param fileName    文件名称
     */
    public static void export(List<?> list, Map<String, String> headerAlias, String fileName) {
        HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getResponse();
        if (response == null) {
            return;
        }
        try (ExcelWriter writer = cn.hutool.poi.excel.ExcelUtil.getWriter();
             ServletOutputStream out = response.getOutputStream()) {

            writer.setHeaderAlias(headerAlias);
            writer.setOnlyAlias(true);

            writer.write(list, true);

            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
            response.setHeader("Content-Disposition", "attachment;filename=" + URLUtil.encode(fileName));

            writer.flush(out, true);
        } catch (IOException e) {
            log.error(e.getMessage(), e);
        }
    }
}
